package info.yaohua.servlet;

import info.yaohua.util.SessionNull;
import info.yaohua.dao.Ac02Dao;
import info.yaohua.dto.Ac01Dto;
import info.yaohua.dto.Ac02Dto;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

/**
 * Servlet implementation class PostServlet
 */
@WebServlet("/PostServlet")
public class PostServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private  String savePath;
	
	public void init(ServletConfig config)
	{
		savePath = config.getInitParameter("savePath");
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PostServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		HttpSession session = request.getSession();
		if (session == null || session.getAttribute("ac01")==null) {
			SessionNull.forwordTo(request, response);
		} else {
			Ac02Dao ac02Dao = new Ac02Dao();
			Ac02Dto ac02Dto ;
			//指定所上传的文件，上传成功后，在硬盘上的保存位置  
			//String filePath=request.getServletContext().getRealPath(savePath);   
			String saveDictionary = request.getServletContext().getRealPath(savePath);

			//如果指定的文件夹不存在的话
			File fileDictionary = new File(saveDictionary);
			if(fileDictionary.exists())
			{
				System.out.println("提示："+saveDictionary +  "已经存在！");
			}
			else
			{
				fileDictionary.mkdirs();
				System.out.println("成功创建 "+saveDictionary);
			}
			
			//限定所上传文件的合计大小，默认为1MB。这里设置的不是单个文件，而是上传的所有文件的总大小
			int maxPostSize = 200 * 1024 * 1024;
			
			DefaultFileRenamePolicy dfrp = new DefaultFileRenamePolicy();
			MultipartRequest multi = new MultipartRequest(request, saveDictionary, maxPostSize, "UTF-8", dfrp);
			
			//本人测试的结果却是：若未显式new DefaultFileRenamePolicy()，此时若上传同名文件，则先前的文件会被后面上传的文件覆盖掉
			//MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "UTF-8");
			ArrayList<String> list = new ArrayList<String>();
			//输出所上传的文件的信息
			Enumeration fileNames = multi.getFileNames();
			while(fileNames.hasMoreElements()){
				String fileName = (String)fileNames.nextElement();
				if(null != multi.getFile(fileName)){
					String lastFileName =savePath + "/" + multi.getFilesystemName(fileName);
					
					list.add(lastFileName);
				}
			}
			
			
			//清空session 中的一些字段
			session.removeAttribute("postMessage");
			session.removeAttribute("sac001");
			session.removeAttribute("sac002");
			session.removeAttribute("sac003");
			session.removeAttribute("id");
			session.removeAttribute("sac006");
			session.removeAttribute("sac007");
			session.removeAttribute("sac008");
			
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			String sac001 = multi.getParameter("sac001");
			String sac002 = multi.getParameter("sac002");
			String sac003 = multi.getParameter("sac003");
			String id = multi.getParameter("id");
			String postMessage;
			
			request.setAttribute("sac001", sac001);
			request.setAttribute("sac002", sac002);
			request.setAttribute("sac003", sac003);
			request.setAttribute("id", id);
		
			///////////////
			//判断是新增还是更新
			/////////////
			Ac01Dto ac01Dto = (Ac01Dto) session.getAttribute("ac01");
			if (sac001.equals("") || sac002.equals("") || sac003.equals("")) {
				postMessage = "标题，正文，标签都不能为空！";
				request.setAttribute("postMessage", postMessage);
				RequestDispatcher view1 = request
						.getRequestDispatcher("/post.jsp");
				view1.forward(request, response);
			} else {
			if(id==null || id.equals(""))//新增
			{
				
				ac02Dto = new Ac02Dto();
				ac02Dto.setSac001(sac001);
				ac02Dto.setSac002(sac002);
				ac02Dto.setSac003(sac003);
				ac02Dto.setAac001(ac01Dto.getAac001());
				ac02Dto.setSac004(new Date(System.currentTimeMillis()));
				ac02Dto.setSac005(new Date(System.currentTimeMillis()));
				if(list.size()==1)
				{
					ac02Dto.setSac006((String) list.get(0));
				}
				if(list.size()==2)
				{
					ac02Dto.setSac006((String) list.get(0));
					ac02Dto.setSac006((String) list.get(1));
				}
				if(list.size()==3)
				{
					ac02Dto.setSac006((String) list.get(0));
					ac02Dto.setSac007((String) list.get(1));
					ac02Dto.setSac008((String) list.get(2));
				}
				request.setAttribute("sac006", ac02Dto.getSac006());
				request.setAttribute("sac007", ac02Dto.getSac007());
				request.setAttribute("sac008", ac02Dto.getSac008());
				try {
					int id_new = ac02Dao.doStore(ac02Dto);
					if (id_new != -1) {
						postMessage = "保存成功！";
						request.setAttribute("id", id_new);
						request.setAttribute("postMessage", postMessage);
						RequestDispatcher view1 = request
								.getRequestDispatcher("/post.jsp");
						view1.forward(request, response);
					} else {
						postMessage = "保存失败！";
						request.setAttribute("postMessage", postMessage);
						RequestDispatcher view1 = request
								.getRequestDispatcher("/post.jsp");
						view1.forward(request, response);
					}
				} catch (NamingException | SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else//更新
			{
				request.setAttribute("id", id);
				ac02Dto = new Ac02Dto();
				ac02Dto.setId(Integer.parseInt(id));
				try {
					ac02Dto = ac02Dao.findAc02ById(ac02Dto);
					ac02Dto.setSac001(sac001);
					ac02Dto.setSac002(sac002);
					ac02Dto.setSac003(sac003);
					ac02Dto.setSac004(new Date(System.currentTimeMillis()));
					if(list.size()==1)
					{
						ac02Dto.setSac006((String) list.get(0));
						request.setAttribute("sac006", ac02Dto.getSac006());
						
					}
					if(list.size()==2)
					{
						ac02Dto.setSac006((String) list.get(0));
						ac02Dto.setSac007((String) list.get(1));
						request.setAttribute("sac006", ac02Dto.getSac006());
						request.setAttribute("sac007", ac02Dto.getSac007());
					
					}
					if(list.size()==3)
					{
						ac02Dto.setSac006((String) list.get(0));
						ac02Dto.setSac007((String) list.get(1));
						ac02Dto.setSac008((String) list.get(2));
						request.setAttribute("sac006", ac02Dto.getSac006());
						request.setAttribute("sac007", ac02Dto.getSac007());
						request.setAttribute("sac008", ac02Dto.getSac008());
					}
					request.setAttribute("sac006", ac02Dto.getSac006());
					request.setAttribute("sac007", ac02Dto.getSac007());
					request.setAttribute("sac008", ac02Dto.getSac008());
					int success = ac02Dao.doUpdateById(ac02Dto);
					if(success==0)
					{
						postMessage = "更新失败！";
						request.setAttribute("postMessage", postMessage);
						RequestDispatcher view1 = request
								.getRequestDispatcher("/post.jsp");
						view1.forward(request, response);
					}
					else
					{
						postMessage = "更新成功！！";
						request.setAttribute("postMessage", postMessage);
						RequestDispatcher view1 = request
								.getRequestDispatcher("/post.jsp");
						view1.forward(request, response);
					}
				} catch (NamingException | SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		
			
			
			
				
			}
		}
	}
}
